package com.woniu.liuzhougov.WorkPlan.controller;

import com.woniu.liuzhougov.WorkPlan.Enum.PlanEnum;
import com.woniu.liuzhougov.WorkPlan.Enum.PlanLog;
import com.woniu.liuzhougov.WorkPlan.Enum.PlanServiceEnum;
import com.woniu.liuzhougov.WorkPlan.dto.PlanDTO;
import com.woniu.liuzhougov.WorkPlan.service.PlanService;
import com.woniu.liuzhougov.WorkPlan.util.IJSONResult;
import com.woniu.liuzhougov.authorityControl.constant.UserConstant;
import com.woniu.liuzhougov.authorityControl.pojo.User;
import com.woniu.liuzhougov.systemSettings.pojo.Log;
import com.woniu.liuzhougov.systemSettings.service.LogService;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: 生成工作计划详情word文件
 * @Author: junzhao
 * @Date: 2019-04-28 14:24
 */
@RestController
public class PlanWord {

    @Autowired
    private LogService logService;

    @Autowired
    private PlanService planService;

    @RequestMapping(value = "/plan/word")
    public IJSONResult getWord(@RequestParam("planId") Integer planId,
                               HttpServletRequest request,
                               HttpServletResponse response) throws UnsupportedEncodingException {
        User user = (User) request.getSession().getAttribute(UserConstant.CURRENT_USER);
        logService.insert(new Log(0, PlanLog.word.getType(),user.getUserId()));


        // 清除buffer缓存
        response.reset();
        //通过传入的ID查询到当前这个计划的内容
        PlanDTO planDTO = planService.selectByPrimaryKeyAndUserId(planId);
        // 指定下载的文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(planDTO.getPlanTime());
        String fileName =planDTO.getDepartmentName()+time+planDTO.getPlanTypeName()+"工作计划";
        response.setHeader("Content-Disposition", "attachment;filename=" +new String(fileName.getBytes("gbk"), "iso8859-1")+ ".docx");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("utf-8");

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        XWPFDocument xwpfDocument = null;
        try {
            xwpfDocument = this.outPutWord(planDTO);
            OutputStream output;
            try {
                output = response.getOutputStream();
                BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
                bufferedOutPut.flush();
                xwpfDocument.write(bufferedOutPut);
                bufferedOutPut.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception e1){
            e1.printStackTrace();
        }
        return null;
    }




    /**
     * 生成工作计划word到本地
     * @param planDTO
     */
    public XWPFDocument outPutWord(PlanDTO planDTO) throws Exception{
        //时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String palnTime = sdf.format(planDTO.getPlanTime());
        String planStartTime = sdf.format(planDTO.getPlanStartTime());
        String planEndTime = sdf.format(planDTO.getPlanEndTime());

        XWPFDocument document= new XWPFDocument();
        //Write the Document in file system
        //添加标题
        XWPFParagraph titleParagraph = document.createParagraph();
        //设置段落居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun titleParagraphRun = titleParagraph.createRun();

        titleParagraphRun.setText(planDTO.getDepartmentName()+"工作计划");
        titleParagraphRun.setColor("000000");
        titleParagraphRun.setFontSize(20);

        //段落
        XWPFParagraph firstParagraph = document.createParagraph();
        XWPFRun run = firstParagraph.createRun();
        run.setText("部门:"+planDTO.getDepartmentName());
        run.setColor("696969");
        run.setFontSize(16);

        //设置段落背景颜色
        CTShd cTShd = run.getCTR().addNewRPr().addNewShd();
        cTShd.setVal(STShd.CLEAR);
        //换行
        XWPFParagraph paragraph1 = document.createParagraph();
        XWPFRun paragraphRun1 = paragraph1.createRun();
        paragraphRun1.setText("\r");

        //基本信息表格
        XWPFTable infoTable = document.createTable();
        //去表格边框
        infoTable.getCTTbl().getTblPr().unsetTblBorders();

        //列宽自动分割
        CTTblWidth infoTableWidth = infoTable.getCTTbl().addNewTblPr().addNewTblW();
        infoTableWidth.setType(STTblWidth.AUTO);
        infoTableWidth.setW(BigInteger.valueOf(9072));

        //表格第一行
        XWPFTableRow infoTableRowOne = infoTable.getRow(0);
        infoTableRowOne.getCell(0).setText("发布者名称:");
        infoTableRowOne.addNewTableCell().setText(planDTO.getUserName());

        //表格第二行
        XWPFTableRow infoTableRowTwo = infoTable.createRow();
        infoTableRowTwo.getCell(0).setText("发布时间:");
        infoTableRowTwo.getCell(1).setText(palnTime);

        //表格第三行
        XWPFTableRow infoTableRowThree = infoTable.createRow();
        infoTableRowThree.getCell(0).setText("工作计划类型:");
        infoTableRowThree.getCell(1).setText(planDTO.getPlanTypeName());

        //表格第四行
        XWPFTableRow infoTableRowFour = infoTable.createRow();
        infoTableRowFour.getCell(0).setText("工作计划开始时间:");
        infoTableRowFour.getCell(1).setText(planStartTime);

        //表格第五行
        XWPFTableRow infoTableRowFive = infoTable.createRow();
        infoTableRowFive.getCell(0).setText("工作计划结束时间:");
        infoTableRowFive.getCell(1).setText(planEndTime);
        //表格第六行
        XWPFTableRow infoTableRowSix = infoTable.createRow();
        infoTableRowSix.getCell(0).setText("工作计划内容:");
        infoTableRowSix.getCell(2);

        //文本段落
        XWPFParagraph firstParagraph2 = document.createParagraph();
        XWPFRun run2 = firstParagraph2.createRun();
        run2.setText("        "+planDTO.getPlanContent());
        run2.setFontSize(12);

        CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
        XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);

        //添加页眉
        CTP ctpHeader = CTP.Factory.newInstance();
        CTR ctrHeader = ctpHeader.addNewR();
        CTText ctHeader = ctrHeader.addNewT();
        String headerText = "ctpHeader";
        ctHeader.setStringValue(headerText);
        XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, document);
        //设置为右对齐
        headerParagraph.setAlignment(ParagraphAlignment.RIGHT);
        XWPFParagraph[] parsHeader = new XWPFParagraph[1];
        parsHeader[0] = headerParagraph;
        policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);

        //添加页脚
        CTP ctpFooter = CTP.Factory.newInstance();
        CTR ctrFooter = ctpFooter.addNewR();
        CTText ctFooter = ctrFooter.addNewT();
        String footerText = "ctpFooter";
        ctFooter.setStringValue(footerText);
        XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, document);
        headerParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFParagraph[] parsFooter = new XWPFParagraph[1];
        parsFooter[0] = footerParagraph;
        policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);
        return document;
    }
}
